package cn.edu.zime.tjh.iotapp;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import android.graphics.SurfaceTexture;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import java.io.ByteArrayOutputStream;

public class InteractionActivity extends AppCompatActivity {
    
    private static final String TAG = "InteractionActivity";
    
    private EditText etServerUrl;
    private Button btnConnect;
    private Button btnScan;
    private Button btnBack;
    private TextView tvMessage;
    
    private WebSocketClient webSocketClient;
    private boolean isConnected = false;
    
    // 扫码结果处理器
    private ActivityResultLauncher<Intent> scanLauncher;
    
    // 传感器相关变量
    private SensorManager sensorManager;
    private Sensor lightSensor;
    private Sensor accelerometerSensor;
    private LocationManager locationManager;
    private boolean isSendingData = false;
    private Handler dataHandler = new Handler();
    private Runnable dataSendTask;
    
    // 添加聊天相关UI元素
    private ListView chatListView;
    private EditText chatEditText;
    private Button sendChatButton;
    private List<ChatMessage> chatMessages;
    private ChatAdapter chatAdapter;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interaction);
        
        // 初始化UI组件
        etServerUrl = findViewById(R.id.etUsername);
        btnConnect = findViewById(R.id.go);
        tvMessage = findViewById(R.id.tvMessage);
        
        // 初始化聊天相关UI
        chatListView = findViewById(R.id.chatListView);
        chatEditText = findViewById(R.id.chatEditText);
        sendChatButton = findViewById(R.id.sendChatButton);
        
        // 初始化聊天消息列表和适配器
        chatMessages = new ArrayList<>();
        chatAdapter = new ChatAdapter();
        chatListView.setAdapter(chatAdapter);
        
        // 设置发送聊天消息按钮点击事件
        sendChatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendChatMessage();
            }
        });
        
        // 初始化扫码结果处理器
        scanLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null && data.hasExtra("SCAN_RESULT")) {
                        String scanResult = data.getStringExtra("SCAN_RESULT");
                        etServerUrl.setText(scanResult);
                        // 自动尝试连接
                        connectToServer(scanResult);
                    }
                }
            }
        );
        
        // 初始化传感器
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        
        // 初始化位置服务
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        // 创建数据发送任务
        dataSendTask = new Runnable() {
            @Override
            public void run() {
                if (isConnected && webSocketClient != null) {
                    sendSensorData();
                    // 每2秒发送一次数据
                    dataHandler.postDelayed(this, 2000);
                }
            }
        };
    }
    
    public void connection(View view) {
        String serverUrl = etServerUrl.getText().toString().trim();
        if (serverUrl.isEmpty()) {
            showMessage("请输入服务器地址");
            return;
        }
        
        // 如果已连接，则断开连接
        if (isConnected && webSocketClient != null) {
            webSocketClient.close();
            btnConnect.setText("确认连接");
            showMessage("已断开连接");
            isConnected = false;
            return;
        }
        
        // 连接服务器
        connectToServer(serverUrl);
    }
    
    private void connectToServer(String serverUrl) {
        try {
            // 确保URL格式正确
            if (!serverUrl.startsWith("ws://") && !serverUrl.startsWith("wss://")) {
                serverUrl = "ws://" + serverUrl;
            }
            
            showMessage("正在连接服务器: " + serverUrl);
            URI serverUri = new URI(serverUrl);
            
            // 连接超时设置（更长的超时时间）
            int connectTimeout = 10000; // 10秒
            
            webSocketClient = new WebSocketClient(serverUri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.d(TAG, "WebSocket连接成功");
                    runOnUiThread(() -> {
                        isConnected = true;
                        btnConnect.setText("断开连接");
                        showMessage("已连接到服务器");
                        
                        // 开始传感器监听
                        startSendingData();
                    });
                    
                    // 发送初始消息
                    webSocketClient.send("客户端已连接");
                }
                
                @Override
                public void onMessage(String message) {
                    Log.d(TAG, "收到消息: " + message);
                    runOnUiThread(() -> {
                        showMessage("收到消息: " + message);
                        
                        // 处理收到的消息
                        try {
                            JSONObject data = new JSONObject(message);
                            String type = data.optString("type", "");
                            
                            if (type.equals("chat")) {
                                String sender = data.getString("sender");
                                String chatMessage = data.getString("message");
                                addChatMessage(sender, chatMessage, false);
                            } else if (type.equals("photo_request")) {
                                // 收到拍照请求，启动前置摄像头拍照
                                showMessage("收到拍照请求，正在处理...");
                                takeSilentPhoto();
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "解析消息错误: " + e.getMessage());
                        }
                    });
                }
                
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    Log.d(TAG, "WebSocket连接关闭: " + reason);
                    runOnUiThread(() -> {
                        isConnected = false;
                        btnConnect.setText("确认连接");
                        showMessage("连接已关闭: " + reason);
                        
                        // 停止发送数据
                        stopSendingData();
                    });
                }
                
                @Override
                public void onError(Exception ex) {
                    Log.e(TAG, "WebSocket错误: " + ex.getMessage());
                    runOnUiThread(() -> {
                        isConnected = false;
                        btnConnect.setText("确认连接");
                        showMessage("连接错误: " + ex.getMessage());
                    });
                }
            };
            
            // 设置连接超时
            webSocketClient.setConnectionLostTimeout(30); // 30秒
            
            // 在新线程中连接WebSocket，带超时处理
            new Thread(() -> {
                try {
                    boolean connected = webSocketClient.connectBlocking(connectTimeout, java.util.concurrent.TimeUnit.MILLISECONDS);
                    if (!connected) {
                        runOnUiThread(() -> showMessage("连接超时，请检查服务器地址和网络连接"));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    runOnUiThread(() -> showMessage("连接被中断"));
                }
            }).start();
            
        } catch (URISyntaxException e) {
            e.printStackTrace();
            showMessage("服务器地址无效");
        }
    }
    
    public void InteractionScan(View view) {
        // 启动扫码界面
        try {
            Intent intent = new Intent(this, ScanActivity.class);
            scanLauncher.launch(intent);
        } catch (Exception e) {
            e.printStackTrace();
            showMessage("启动扫码失败: " + e.getMessage());
        }
    }
    
    public void InteractionBack(View view) {
        // 断开连接并返回
        if (webSocketClient != null) {
            webSocketClient.close();
        }
        finish();
    }
    
    private void showMessage(String message) {
        tvMessage.setText(message);
        tvMessage.setVisibility(View.VISIBLE);
        // 只在重要事件时显示Toast
        if (message.contains("已连接") || message.contains("连接已关闭") || message.contains("请输入")) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        } else {
            Log.d(TAG, message);
        }
    }
    
    // 传感器事件监听器
    private SensorEventListener lightSensorListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
                float lightValue = event.values[0];
                try {
                    JSONObject data = new JSONObject();
                    data.put("type", "light");
                    data.put("value", lightValue);
                    
                    if (isConnected && webSocketClient != null) {
                        webSocketClient.send(data.toString());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "发送光照数据错误: " + e.getMessage());
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // 不需要处理
        }
    };

    private SensorEventListener accelerometerListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                
                try {
                    JSONObject data = new JSONObject();
                    data.put("type", "acceleration");
                    data.put("x", x);
                    data.put("y", y);
                    data.put("z", z);
                    
                    if (isConnected && webSocketClient != null) {
                        webSocketClient.send(data.toString());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "发送加速度数据错误: " + e.getMessage());
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // 不需要处理
        }
    };

    // 位置监听器
    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            try {
                JSONObject data = new JSONObject();
                data.put("type", "location");
                data.put("latitude", location.getLatitude());
                data.put("longitude", location.getLongitude());
                
                if (isConnected && webSocketClient != null) {
                    webSocketClient.send(data.toString());
                }
            } catch (Exception e) {
                Log.e(TAG, "发送位置数据错误: " + e.getMessage());
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

    // 开始发送传感器数据
    private void startSendingData() {
        if (!isSendingData) {
            // 注册传感器监听器
            if (lightSensor != null) {
                sensorManager.registerListener(lightSensorListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
            }
            
            if (accelerometerSensor != null) {
                sensorManager.registerListener(accelerometerListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
            }
            
            // 请求位置更新
            try {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
                }
            } catch (Exception e) {
                Log.e(TAG, "位置监听错误: " + e.getMessage());
            }
            
            // 启动定期发送任务
            dataHandler.post(dataSendTask);
            isSendingData = true;
        }
    }

    // 停止发送传感器数据
    private void stopSendingData() {
        if (isSendingData) {
            // 取消传感器监听
            sensorManager.unregisterListener(lightSensorListener);
            sensorManager.unregisterListener(accelerometerListener);
            
            // 取消位置更新
            locationManager.removeUpdates(locationListener);
            
            // 取消定期发送任务
            dataHandler.removeCallbacks(dataSendTask);
            isSendingData = false;
        }
    }

    // 手动发送传感器数据
    private void sendSensorData() {
        // 此方法可以用于定期发送数据或在用户请求时发送
        // 实际实现可以根据需要调整
    }
    
    // 发送聊天消息
    private void sendChatMessage() {
        String message = chatEditText.getText().toString().trim();
        if (message.isEmpty() || !isConnected || webSocketClient == null) {
            return;
        }
        
        try {
            JSONObject chatData = new JSONObject();
            chatData.put("type", "chat");
            chatData.put("sender", "设备端");
            chatData.put("message", message);
            
            webSocketClient.send(chatData.toString());
            
            // 添加消息到本地列表
            addChatMessage("设备端", message, true);
            
            // 清空输入框
            chatEditText.setText("");
        } catch (JSONException e) {
            Log.e(TAG, "发送聊天消息错误: " + e.getMessage());
        }
    }
    
    // 添加聊天消息到列表
    private void addChatMessage(String sender, String message, boolean isFromMe) {
        ChatMessage chatMessage = new ChatMessage(sender, message, isFromMe);
        chatMessages.add(chatMessage);
        chatAdapter.notifyDataSetChanged();
        
        // 滚动到最新消息
        chatListView.smoothScrollToPosition(chatMessages.size() - 1);
    }
    
    // 聊天消息数据类
    private static class ChatMessage {
        String sender;
        String message;
        boolean isFromMe;
        
        ChatMessage(String sender, String message, boolean isFromMe) {
            this.sender = sender;
            this.message = message;
            this.isFromMe = isFromMe;
        }
    }
    
    // 聊天消息适配器
    private class ChatAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return chatMessages.size();
        }
        
        @Override
        public ChatMessage getItem(int position) {
            return chatMessages.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(InteractionActivity.this)
                        .inflate(R.layout.item_chat_message, parent, false);
            }
            
            ChatMessage message = getItem(position);
            
            TextView senderTextView = convertView.findViewById(R.id.senderTextView);
            TextView messageTextView = convertView.findViewById(R.id.messageTextView);
            LinearLayout messageContainer = convertView.findViewById(R.id.messageContainer);
            
            senderTextView.setText(message.sender);
            messageTextView.setText(message.message);
            
            // 根据消息发送方设置不同的样式
            if (message.isFromMe) {
                // 设备发送的消息靠右对齐
                senderTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
                messageContainer.setGravity(android.view.Gravity.END);
            } else {
                // 管理员发送的消息靠左对齐
                senderTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                messageContainer.setGravity(android.view.Gravity.START);
            }
            
            return convertView;
        }
    }
    
    // 使用前置摄像头静默拍照
    private void takeSilentPhoto() {
        // 确保有相机权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1002);
            return;
        }
        
        Camera camera = null;
        try {
            // 寻找前置摄像头
            int cameraId = findFrontFacingCamera();
            if (cameraId >= 0) {
                // 使用前置摄像头
                camera = Camera.open(cameraId);
            } else {
                // 如果前置摄像头不可用，使用默认摄像头
                camera = Camera.open();
            }
            
            // 确保相机成功打开
            if (camera == null) {
                showMessage("无法打开摄像头");
                return;
            }
            
            // 设置参数
            Camera.Parameters parameters = camera.getParameters();
            
            // 获取预览尺寸
            List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
            Camera.Size optimalSize = getOptimalPreviewSize(sizes, 640, 480);
            parameters.setPreviewSize(optimalSize.width, optimalSize.height);
            
            // 设置照片质量参数
            parameters.setJpegQuality(70);
            camera.setParameters(parameters);
            
            // 创建临时的SurfaceTexture以启动预览
            SurfaceTexture surfaceTexture = new SurfaceTexture(0);
            camera.setPreviewTexture(surfaceTexture);
            camera.startPreview();
            
            // 拍照
            final Camera finalCamera = camera; // 为回调保存引用
            camera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera cam) {
                    try {
                        // 处理图片数据
                        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                        
                        // 旋转图片（前置摄像头通常需要旋转）
                        Matrix matrix = new Matrix();
                        matrix.postRotate(270);
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                        
                        // 压缩图片
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
                        byte[] compressedData = baos.toByteArray();
                        
                        // 转换为Base64
                        String base64Image = Base64.encodeToString(compressedData, Base64.DEFAULT);
                        
                        // 发送给管理端
                        sendPhotoToAdmin(base64Image);
                        
                        // 释放相机资源
                        finalCamera.stopPreview();
                        finalCamera.release();
                        
                    } catch (Exception e) {
                        Log.e(TAG, "处理照片错误: " + e.getMessage());
                        // 释放相机资源
                        finalCamera.release();
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "相机操作错误: " + e.getMessage());
            showMessage("相机操作失败: " + e.getMessage());
            if (camera != null) {
                camera.release();
            }
        }
    }
    
    // 查找前置摄像头ID
    private int findFrontFacingCamera() {
        int cameraId = -1;
        // 查找前置摄像头
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                break;
            }
        }
        return cameraId;
    }
    
    // 获取最佳预览尺寸
    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        
        if (sizes == null) return null;
        
        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;
        
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - h) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - h);
            }
        }
        
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - h) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - h);
                }
            }
        }
        
        return optimalSize;
    }
    
    // 发送照片到管理端
    private void sendPhotoToAdmin(String base64Image) {
        if (isConnected && webSocketClient != null) {
            try {
                JSONObject photoData = new JSONObject();
                photoData.put("type", "photo");
                photoData.put("data", base64Image);
                
                webSocketClient.send(photoData.toString());
                showMessage("照片已发送至管理端");
            } catch (JSONException e) {
                Log.e(TAG, "发送照片错误: " + e.getMessage());
                showMessage("发送照片失败: " + e.getMessage());
            }
        } else {
            showMessage("连接已断开，无法发送照片");
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1002) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限获取成功，重新尝试拍照
                takeSilentPhoto();
            } else {
                showMessage("需要相机权限才能拍照");
            }
        }
    }
    
    @Override
    protected void onDestroy() {
        stopSendingData();
        if (webSocketClient != null) {
            webSocketClient.close();
        }
        super.onDestroy();
    }
}
